package br.com.findme.findmeserver.controle;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import br.com.findme.findmeserver.dao.HibernateUtils;
import br.com.findme.findmeserver.entidade.Grupo;
import br.com.findme.findmeserver.mensagem.Mensagem;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Servlet implementation class ListarGruposDoUsuario
 */
public class ListarGruposDoLider extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListarGruposDoLider() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doProcess(request, response);
	}
	
	protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			Mensagem m = null;
			
			try {
				
				String pIdUsuario = request.getParameter("id_usuario");
				
					
				Session session = HibernateUtils.openSession();
				
				Criteria c = session.createCriteria(Grupo.class);
								
				c.add( Restrictions.eq("ativo", 1));
				c.add( Restrictions.eq("usuario.id", Integer.parseInt(pIdUsuario)));
				
				List grupos = c.list();
				
				m = new Mensagem(Mensagem.STATUS_SUCESSO, "Listagem de grupos realizada com sucesso.", grupos);
							
			} catch (Exception e) {
				m = new Mensagem(Mensagem.STATUS_ERRO, "Não foi possível listar os grupos.");			
			}
			
			PrintWriter pw = response.getWriter();
			
			GsonBuilder gb = new GsonBuilder();
			Gson gson = gb.registerTypeAdapter(Grupo.class, Grupo.toJSON()).create();
			String retorno = m.toString(gson);
			pw.append(retorno);
			
	}
	
	

}
